from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QProgressBar, QLabel, QMessageBox
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
import urllib.request
import subprocess
import requests
import logging

# 配置日志记录
logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')


# 嵌入的批处理脚本内容
bat_content = """@echo off
setlocal

:: 获取当前目录
set "current_dir=%~dp0"

:: 等待一段时间，确保当前进程已经关闭
timeout /t 5 /nobreak >nul

:: 删除旧的可执行文件
del "%current_dir%app.exe"

:: 重命名新的可执行文件为旧的可执行文件名
ren "%current_dir%app_new.exe" "app.exe"

:: 显示消息框并等待用户确认
msg * "update success"

:: 退出脚本
exit

"""

class DownloadThread(QThread):
    progress = pyqtSignal(int)
    finished = pyqtSignal(bool)
    error = pyqtSignal(str)

    def __init__(self, update_url, save_path):
        super().__init__()
        self.update_url = update_url
        self.save_path = save_path

    def run(self):
        try:
            def reporthook(block_num, block_size, total_size):
                read_so_far = block_num * block_size
                if total_size > 0:
                    percent = int((read_so_far / total_size) * 100)
                    self.progress.emit(percent)

            urllib.request.urlretrieve(self.update_url, self.save_path, reporthook=reporthook)
            self.finished.emit(True)
        except Exception as e:
            self.error.emit(str(e))
            self.finished.emit(False)


class CheckUpdateThread(QThread):
    update_available = pyqtSignal(dict)
    no_update = pyqtSignal(str)
    error = pyqtSignal(str)

    def __init__(self, current_version):
        super().__init__()
        self.current_version = current_version

    def run(self):
        try:
            url = "http://chatai.wenba.gd.cn:22007/analyseApi/chatai/update/getUpdateUrl?updateId=2"
            response = requests.get(url)
            if response.status_code == 200:
                update_info = response.json()
                latest_version = update_info['data']['updateVersion']
                if latest_version > self.current_version:
                    self.update_available.emit(update_info['data'])
                else:
                    self.no_update.emit("没有可更新的.")
            else:
                self.error.emit(f"更新失败的信息: {response.status_code}")
        except Exception as e:
            self.error.emit(f"错误的刷新更新信息: {e}")


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.current_version = 1  # 假设当前版本为1
        self.check_for_updates()

    def initUI(self):
        self.setWindowTitle('自动更新例子')
        self.setGeometry(100, 100, 400, 200)

        layout = QVBoxLayout()

        self.label = QLabel("Checking for updates...")
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)

        self.button = QPushButton("Check for Updates")
        self.button.clicked.connect(self.check_for_updates)
        layout.addWidget(self.button)

        self.progressBar = QProgressBar()
        self.progressBar.setVisible(False)
        layout.addWidget(self.progressBar)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def check_for_updates(self):
        self.label.setText("检测是否有更新啊")
        self.thread = CheckUpdateThread(self.current_version)
        self.thread.update_available.connect(self.update_available)
        self.thread.no_update.connect(self.show_no_update_message)
        self.thread.error.connect(self.show_error_message)
        self.thread.start()

    def update_available(self, update_info):
        reply = QMessageBox.question(self, '有可用更新',
                                     f"一个新的版本是可以用的: {update_info['updateVersion']}\n你想要下载它?",
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.download_update(update_info['updateUrl'], 'app_new.exe')

    def download_update(self, update_url, save_path):
        self.thread = DownloadThread(update_url, save_path)
        self.thread.progress.connect(self.update_progress)
        self.thread.finished.connect(self.download_finished)
        self.thread.error.connect(self.show_error_message)
        self.thread.start()

    def update_progress(self, value):
        self.progressBar.setValue(value)
        self.progressBar.setVisible(True)

    def download_finished(self, success):
        if success:
            QMessageBox.information(self, '下载完成', '应用进行重启')
            self.run_update_script()
        else:
            QMessageBox.critical(self, '下载失败', '下载更新失败')
        self.progressBar.setVisible(False)

    def show_no_update_message(self, message):
        QMessageBox.information(self, '不更新', message)

    def show_error_message(self, message):
        QMessageBox.critical(self, '错误', message)

    def run_update_script(self):
        try:
            # 创建批处理脚本
            with open('update.bat', 'w', encoding='utf-8') as f:
                f.write(bat_content)

            # 使用 QTimer 延迟关闭当前进程
            QTimer.singleShot(3000, self.close_and_run_update_script)
        except Exception as e:
            QMessageBox.critical(self, '重启失败', f"失败的重启应用: {str(e)}")

    def close_and_run_update_script(self):
        # 关闭当前应用程序
        self.close()
        # 运行批处理脚本
        subprocess.Popen(['update.bat'], shell=True)
        # 退出进程
        sys.exit(0)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())